package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.*;
import com.erp.gather.domain.bo.ErpCollectProductUploadTestTaskBo;
import com.erp.gather.domain.vo.ErpCollectProductUploadTestTaskVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IErpCollectProductUploadTestTaskService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpCollectProduct;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.ruoyi.gather.api.domain.ErpSellerCollectProduct;
import com.ruoyi.gather.api.domain.ErpSellerCollectProductExpand;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 采集商品上传测试任务Service业务层处理
 *
 * @author erp
 * @date 2023-05-18
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductUploadTestTaskServiceImpl implements IErpCollectProductUploadTestTaskService {

    private final ErpCollectProductUploadTestTaskMapper baseMapper;
    private final ErpCollectProductCategoryMapper erpCollectProductCategoryMapper;
    private final ErpProductAutoTestStoreMapper erpProductAutoTestStoreMapper;
    private final ErpSellerCollectProductMapper erpSellerCollectProductMapper;
    private final ErpSellerCollectProductExpandMapper erpSellerCollectProductExpandMapper;
    private final ErpCollectProductUploadTestTaskMapper erpCollectProductUploadTestTaskMapper;
    private final ErpCollectProductExpandMapper erpCollectProductExpandMapper;
    private final ErpCollectProductMapper erpCollectProductMapper;

    /**
     * 查询采集商品上传测试任务
     */
    @Override
    public ErpCollectProductUploadTestTaskVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询采集商品上传测试任务列表
     */
    @Override
    public TableDataInfo<ErpCollectProductUploadTestTaskVo> queryPageList(ErpCollectProductUploadTestTaskBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpCollectProductUploadTestTask> lqw = buildQueryWrapper(bo);
        Page<ErpCollectProductUploadTestTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询采集商品上传测试任务列表
     */
    @Override
    public List<ErpCollectProductUploadTestTaskVo> queryList(ErpCollectProductUploadTestTaskBo bo) {
        LambdaQueryWrapper<ErpCollectProductUploadTestTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpCollectProductUploadTestTask> buildQueryWrapper(ErpCollectProductUploadTestTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpCollectProductUploadTestTask> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCollectProductId() != null, ErpCollectProductUploadTestTask::getCollectProductId, bo.getCollectProductId());
        lqw.eq(bo.getStoreId() != null, ErpCollectProductUploadTestTask::getStoreId, bo.getStoreId());
        lqw.eq(bo.getStatus() != null, ErpCollectProductUploadTestTask::getStatus, bo.getStatus());
        lqw.eq(bo.getAddTime() != null, ErpCollectProductUploadTestTask::getAddTime, bo.getAddTime());
        return lqw;
    }

    /**
     * 新增采集商品上传测试任务
     */
    @Override
    public Boolean insertByBo(ErpCollectProductUploadTestTaskBo bo) {
        ErpCollectProductUploadTestTask add = BeanUtil.toBean(bo, ErpCollectProductUploadTestTask.class);
        validEntityBeforeSave(add);
        bo.setType("1");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改采集商品上传测试任务
     */
    @Override
    public Boolean updateByBo(ErpCollectProductUploadTestTaskBo bo) {
        ErpCollectProductUploadTestTask update = BeanUtil.toBean(bo, ErpCollectProductUploadTestTask.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpCollectProductUploadTestTask entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除采集商品上传测试任务
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<ErpCollectProductUploadTestTask> queryWaitUploadProductList() {
        List<ErpCollectProductUploadTestTask> erpCollectProductUploadTestTasks = baseMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductUploadTestTask>()
                        .eq(ErpCollectProductUploadTestTask::getStatus, 0)
        );
        return erpCollectProductUploadTestTasks;
    }

    @Override
    public Integer updateTask(ErpCollectProductUploadTestTask task) {
        return baseMapper.updateById(task);
    }

    /**
     * 获取测试店铺
     *
     * @param collectProductId
     * @return
     */
    @Override
    public R<Object> getAutoTestStoreList(Long collectProductId, Integer type) {
        //获取其最新的一条测试数据
        Long categoryId = null;
        if (type == 1) {
            ErpCollectProduct product = erpCollectProductMapper.selectById(collectProductId);
            categoryId = product.getCategoryId();
        } else {
            ErpSellerCollectProduct sellerCollectProduct = erpSellerCollectProductMapper.selectById(collectProductId);
            categoryId = sellerCollectProduct.getCategoryId();
        }
        //
        try {
            Long topCategoryId = null;
            // 获取商品类目的顶级类目
            ErpCollectProductCategory erpCollectProductCategory = erpCollectProductCategoryMapper
                    .selectOne(new LambdaQueryWrapper<ErpCollectProductCategory>().eq(ErpCollectProductCategory::getId,
                            categoryId));
            if (erpCollectProductCategory.getParentId() == 0) {
                // 顶点
                topCategoryId = erpCollectProductCategory.getId();
            } else {
                // 非顶点
                // 转为数组，获取第数组的第二个对象
                String[] ancestors = erpCollectProductCategory.getAncestors().split(",");
                topCategoryId = Long.valueOf(ancestors[1]);
            }

            // 获取表内有权限的店铺
            LambdaQueryWrapper<ErpProductAutoTestStore> lqw = new LambdaQueryWrapper<ErpProductAutoTestStore>();
            lqw.eq(ErpProductAutoTestStore::getStatus, 1);
            lqw.eq(ErpProductAutoTestStore::getCategoryId, topCategoryId);
            List<ErpProductAutoTestStore> storeList = erpProductAutoTestStoreMapper.selectList(lqw);
            if (storeList != null && storeList.size() > 0) {
                return R.ok(storeList);
            } else {
                return R.fail("暂无可用店铺");
            }
        } catch (Exception e) {
            // 获取类目异常
            return R.fail("获取店铺异常");
        }
    }

    @Override
    public R<Object> cancelUploadTest(ErpCollectProductUploadTestTask task) {
        //根据type判断
        if (task.getType() == 1) {
            ErpCollectProduct product = erpCollectProductMapper.selectById(task.getCollectProductId());
            ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getCollectProductId, product.getId())
            );
            collectProductExpand.setIsUploadTest(0);
            erpCollectProductExpandMapper.updateById(collectProductExpand);
        } else {
            ErpSellerCollectProduct product = erpSellerCollectProductMapper.selectById(task.getCollectProductId());
            ErpSellerCollectProductExpand sellerCollectProductExpand = erpSellerCollectProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerCollectProductExpand>().eq(ErpSellerCollectProductExpand::getCollectProductId, product.getId())
            );
            sellerCollectProductExpand.setIsUploadTest(0);
            erpSellerCollectProductExpandMapper.updateById(sellerCollectProductExpand);
        }
        erpCollectProductUploadTestTaskMapper.deleteById(task);
        return R.ok("已取消测试发布");
    }
}
